#include "videorecorder_cv.h"

#include <QDebug>

VideoRecorder_CV::VideoRecorder_CV(QObject *parent) : BaseRecorder{parent} {}

bool VideoRecorder_CV::openFile(const QString &basename) {
  auto fourcc = m_writer.fourcc('M', 'P', '4', '2');
  cv::Size frameSize(1920, 1080);
  return m_writer.open(basename.toStdString(), fourcc, 60, frameSize);
}

void VideoRecorder_CV::onImage(std::shared_ptr<QImage> img) {
  cv::Mat mat;
  pixmap2Mat(img.get(), &mat);

  cv::Mat mat_mirror_v;
  cv::flip(mat, mat_mirror_v, 0);

  m_writer.write(mat_mirror_v);

}

void VideoRecorder_CV::pixmap2Mat(QImage *img, cv::Mat *mat) {
  if (img->format() == QImage::Format_RGB32) {
    *img = img->convertToFormat(QImage::Format_RGB888);
  }
  *mat = cv::Mat(img->height(), img->width(), CV_8UC3, img->bits(),
                 img->bytesPerLine());
  cv::cvtColor(*mat, *mat, cv::COLOR_RGBA2BGR);
}
